package config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * Created by 张少昆 on 2017/11/6.
 */
@EnableWebMvc
@Configuration
@ComponentScan( basePackages = "test",
                includeFilters = @ComponentScan.Filter( type = FilterType.ANNOTATION, classes = {Controller.class, ControllerAdvice.class} ) )
public class MvcConfig extends WebMvcConfigurerAdapter {

    // 使用common multipart
    @Bean
    public MultipartResolver commonMultipartResolver(){
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        //...
        return resolver;
    }

    // TODO webjar
    // FIXME 这里的请求也会被security拦截啊，需要设置下放行
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        System.out.println("-------------------------webjars映射-----------------------~");
        super.addResourceHandlers(registry);
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/html/**").addResourceLocations("classpath:/html/");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry){
        super.addViewControllers(registry);
        registry.addRedirectViewController("/","/html/index.html");
    }

    @Bean
    public ViewResolver viewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");//classpath:应该也可以
        resolver.setSuffix(".jsp");
        return resolver;
    }
}